<template>
  <BasicModal @register="modalRegister" :okText="SAVE" @ok="onSave" @cancel="onFinish">
    <BasicForm @register="formRegister" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { SAVE, ADD, EDIT } from '/@/constant';

  import { save, update } from '../api';
  import { formSchemas as schemas } from '../schema';
  import { FormTypeEnum } from '/@/enums/formTypeEnum';
  import { RoleListModel, RoleSaveModel, RoleUpdateModel } from '../model';
  import { FormData } from '/@/model/FormData';

  const emit = defineEmits(['onOk', 'register']);

  const typeRef = ref<FormTypeEnum>();
  const [modalRegister, { setModalProps, closeModal }] = useModalInner(
    (data: FormData<RoleListModel>) => {
      const { type, obj } = data;
      typeRef.value = type;
      setModalProps({
        title: type === FormTypeEnum.ADD ? ADD : `${EDIT}-${obj?.name}`,
      });
      if (type === FormTypeEnum.EDIT) {
        setFieldsValue({ ...obj });
      }
    },
  );

  const [formRegister, { validate, resetFields, getFieldsValue, setFieldsValue }] = useForm({
    labelWidth: 120,
    baseColProps: {
      span: 24,
    },
    schemas,
    showSubmitButton: false,
    showResetButton: false,
    actionColOptions: {
      span: 24,
    },
  });

  const onSave = async (e: Event) => {
    const validateRes = await validate();
    if (validateRes) {
      const type = unref(typeRef);
      if (type === FormTypeEnum.ADD) {
        const role: RoleSaveModel = getFieldsValue() as RoleSaveModel;
        save(role).then(() => {
          onFinish();
          emit('onOk', e);
        });
      }

      if (type === FormTypeEnum.EDIT) {
        const role: RoleUpdateModel = getFieldsValue() as RoleUpdateModel;
        update(role).then(() => {
          onFinish();
          emit('onOk', e);
        });
      }
    }
  };
  const onFinish = () => {
    closeModal();
    resetFields();
  };
</script>

<style scoped></style>
